const query = require('../db/index')
const moment = require('moment')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

class UserController {
    static instance
    static getInstance () {
        if (!this.instance) {
            this.instance = new UserController()
        }
        return this.instance
    }
    async register (req, res, next) {
        try {
            // 使用 joi 进行校验定义 使用 @escook/express-joi 进行中间件生成
            // if (!req.body.username || !req.body.password || !req.body.rePassword) {
            //     return res.err('用户名或密码不能为空')
            // }
            const querytSql = 'select * from ev_users where u_username = ?'
            const querytParams = [req.body.username]
            const queryRes = await query(querytSql, querytParams)
            if (queryRes.length > 0) {
                return res.err('用户名被占用，请重新注册')
            }
            const insertSql = 'insert into ev_users(u_username,u_password,u_createTime) values(?,?,?) '
            const insertParams = [
                req.body.username,
                // bcrypt 加密  两个参数 密码，随机盐长度；增强密码安全性
                bcrypt.hashSync(req.body.password, 10),
                moment().format('YYYY-MM-DD HH:mm:ss')
            ]
            const insertRes = await query(insertSql, insertParams)
            if (insertRes && insertRes.affectedRows > 0) {
                res.json({
                    code: 200,
                    msg: '注册成功',
                    data: true
                })
            } else {
                res.err('注册失败')
            }
        } catch (error) {
            console.log('error', error)
            res.err(error, 500)
        }
    }
    async login (req, res, next) {
        try {
            const queryParams = [req.body.username]
            const querySql = 'select * from ev_users where u_username = ?'
            console.log(req.body.password)
            const queryRes = await query(querySql, queryParams)
            if (queryRes && queryRes.length > 0) {
                const qq = bcrypt.compareSync(req.body.password, queryRes[0].u_password)
                if (qq) {
                    const info = { ...queryRes[0] }
                    delete info.u_password
                    delete info.u_user_pic
                    delete info.u_status
                    const token = jwt.sign(info, require('../config/index').encryptionKey.tokenKey, {
                        algorithm: 'HS256',
                        expiresIn: '60h'
                    })
                    res.suc('登录', {
                        token
                    })
                } else {
                    res.err('密码错误')
                }

            } else {
                res.err('用户名错误')
            }
        } catch (error) {
            res.err(error, 500)
        }
    }
}
module.exports = UserController.getInstance()